package downloader

import (
	"gitee.com/Luna-CY/hui-hui/internal/toolbox/downloader"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
)

type ProgressRequest struct {
	Ids []string `json:"ids" validate:"required" minimum:"1" maximum:"1" binding:"required,min=1,dive,uuid"` // 任务ID列表
}

type ProgressResponse struct {
	Data []ProgressTask `json:"data" validate:"required"` // 任务列表
}

type ProgressTask struct {
	Id           string `json:"id" validate:"required"`                    // 任务ID
	State        int    `json:"state" validate:"required" enums:"1,2,3,4"` // 任务状态：下载中、失败、完成、取消
	Message      string `json:"message" validate:"required"`               // 状态描述
	EndTime      int64  `json:"end_time" validate:"required"`              // 结束时间，状态为失败、完成、取消时有效
	DownloadSize int64  `json:"download_size" validate:"required"`         // 已下载的字节数
	Expired      int64  `json:"expired" validate:"required"`               // 文件过期时间，状态为完成时有效
}

func (cls *Downloader) Progress(c *gin.Context) (int, any, error) {
	var body = ProgressRequest{}
	if err := c.ShouldBindJSON(&body); nil != err {
		return response.InvalidRequest, nil, err
	}

	var mapping = map[string]struct{}{}
	for _, id := range body.Ids {
		mapping[id] = struct{}{}
	}

	var tasks = cls.downloader.Tasks()

	var res = ProgressResponse{}
	res.Data = make([]ProgressTask, 0)

	for _, task := range tasks {
		if _, ok := mapping[task.Id]; !ok {
			continue
		}

		var item = ProgressTask{}
		item.Id = task.Id
		item.State = int(task.State)
		item.Message = task.Message
		item.DownloadSize = task.DownloadSize

		if downloader.TaskStateDownloading != task.State {
			item.EndTime = task.EndTime.Unix()
		}

		if downloader.TaskStateComplete == task.State {
			item.Expired = task.EndTime.Add(task.Timeout).Unix()
		}

		res.Data = append(res.Data, item)
	}

	return response.Ok, res, nil
}
